package com.cimr.comm.util;

import cn.hutool.core.lang.Console;
import net.sf.json.JSONObject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by liqi on 2017/8/9.
 */
public class AjaxUtil {

    /**
     * 是否是Ajax请求
     * @param request
     * @return
     */
    public static boolean isAjax(ServletRequest request){
        return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
    }


    /**
     * response 输出JSON
     * @param result
     * @throws IOException
     */
    public static void out(ServletResponse response, Object result){
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.println(JSONObject.fromObject(result).toString());
        } catch (Exception e) {
            Console.error(e, "输出JSON报错。");
        }finally{
            if(null != out){
                out.flush();
                out.close();
            }
        }
    }
}
